package com.biostime.springdraw.modules.sd.service;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.biostime.springdraw.common.utils.StringUtils;
import com.biostime.springdraw.common.wechat.BiostimeWechat;


/**
 * jssdk
 * @author chenweicheng
 * @version 2016-05-11
 */
@Transactional
@Service
public class JssdkService {
	
	
	/**
	 * 获取jssdk列表所需的配置认证信息
	 * @author chenweicheng
	 * @version 2016-05-11
	 */	
	public HashMap<String,Object> jssdk(HttpServletRequest request){
		long timestamp = new Date().getTime();
		SimpleDateFormat sdf =   new SimpleDateFormat( " yyyy-MM-dd HH:mm:ss " );
		String noncestr = "64654654564654";
		String jsticket = null;
		String appId = null;
		String mySign = null;
		String url = null;
		
		byte[] sendBytes1 = HttpRequestService.sendGet(BiostimeWechat.Jsticket, "from=ismart");
		byte[] sendBytes2 = HttpRequestService.sendGet(BiostimeWechat.AppID, "from=ismart");
		
		try {
			
			String jsticketJson=new String( sendBytes1 ,"UTF-8"); 
			String appIdJson=new String( sendBytes2 ,"UTF-8"); 
			url =  "http://wx.biostime.com.cn/wx-test02/springdraw/f/shareIndex" + (StringUtils.isEmpty(request.getQueryString()) ? "" : ("?"+request.getQueryString()));
						
			HashMap<String,String> m = (HashMap<String, String>) BiostimeWechat.Api.toMap(jsticketJson);	
			m = (HashMap<String, String>) BiostimeWechat.Api.toMap(appIdJson);
						
			jsticket = m.get("jsticket");
			appId = m.get("appId");
			
	        SortedMap<Object,Object> parameters = new TreeMap<Object,Object>();  
	        parameters.put("url", url);  
	        parameters.put("jsapi_ticket", jsticket);
	        parameters.put("timestamp", timestamp);  
	        parameters.put("noncestr", noncestr);
	        String characterEncoding = "UTF-8";  
	        mySign = SignService.createSign(characterEncoding,parameters);
					
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		HashMap<String,Object> map = new HashMap<String,Object>();
		map.put("appId", appId);
		map.put("timestamp", timestamp);
		map.put("nonceStr", noncestr);
		map.put("signature",mySign);	
		map.put("url",url);
		
		return map;
	}
  
	
}
